import Vue from 'vue'
import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // 进度条样式
import notification from 'ant-design-vue/es/notification' // NProgress 进度条配置
import { ACCESS_TOKEN } from '@/store/constants'
import { generatorDynamicLayoutRouter } from '@/router/generator-routers'
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/registerResult'] // 白名单
const defaultRoutePath = '/home' // 默认跳转页面

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (Vue.ls.get(ACCESS_TOKEN)) { /* 有登录 */
    if (to.path === '/login') {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      if (!store.getters.name) {
        // 获取用户信息
        store.dispatch('user/getUserInfo').then(res => {
          // 生成动态菜单
          generatorDynamicLayoutRouter().then(() => {
            router.addRoutes(store.getters.addRouters)
            // 请求带有 redirect 重定向时，登录自动重定向到该地址
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,解决浏览器刷新动态路由不在问题（history丢失）
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
        }).catch(() => {
          notification.error({
            message: '错误',
            description: '请求用户信息失败，请重试'
          })
          store.dispatch('user/logout').then(() => {
            next({ path: '/login', query: { redirect: to.fullPath } })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next() // 在免登录白名单，直接进入
    } else {
      next({ path: '/login', query: { redirect: to.fullPath === '/404' ? defaultRoutePath : to.fullPath } })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
